import { inject, injectable } from 'inversify';
import { RoleListModel } from '../models/role.list.model.ts';
import { UsersRolesRepository } from '../data/users.roles.repository.ts';
import { requestWOMeta } from '../data/user.roles.dto.ts';
import { roleDetailMapper } from '../mappers/role.list.mapper.ts';

@injectable()
export class UpdateRoleUseCase {
  constructor(
    @inject(RoleListModel) private roleListModel: RoleListModel,
    @inject(UsersRolesRepository) private rolesRepository: UsersRolesRepository,
  ) {}

  async execute(_id: string, params: requestWOMeta) {
    const currentRoleToUpdate = this.roleListModel.roles.find(
      (role) => role._id === _id,
    );

    if (currentRoleToUpdate) {
      try {
        this.roleListModel.updateRole(roleDetailMapper(params));
        await this.rolesRepository.updateRole(_id, params);
      } catch (e) {
        this.roleListModel.updateRole(currentRoleToUpdate);
      }
    }
  }
}
